package com.wang.project.job;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.wang.project.constant.CommonConstant;
import com.wang.project.constant.UserConstant;
import com.wang.project.model.entity.User;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.wang.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class XxlUserKeyHandleJob {
    /**
     * todo 还未在xxl-job的admin页面设置定时时间
     */

    @Resource
    private UserService userService;

    @XxlJob("TestJob")
    public void test() {
        System.out.println("testJob");
    }

    /**
     * 每30天刷新一次ak sk
     *
     * @param request
     */
    @XxlJob("RefreshKeyHandleJob")
    public void RefreshKeyHandleJob(HttpServletRequest request) {
        log.info("执行xxl-job RefreshKeyHandleJob 三十天定时刷新ak sk");
        List<User> userList = userService.list();
        //刷新没有充钱的用户的ak sk
        List<User> newUserList = userList.stream().map(user -> {
            if (user.getIsVip() != UserConstant.ISVIP) {
                String accessKey = DigestUtil.md5Hex(CommonConstant.SALT + user.getUserAccount() + RandomUtil.randomNumbers(4));
                String secretKey = DigestUtil.md5Hex(CommonConstant.SALT + user.getUserAccount() + RandomUtil.randomNumbers(8));
                user.setAccessKey(accessKey);
                user.setSecretKey(secretKey);
            }
            return user;
        }).collect(Collectors.toList());
        boolean result = userService.saveBatch(newUserList);
        if (!result) {
            log.info("XxlUserKeyHandleJob RefreshKeyHandleJob 刷新用户ak sk错误，请重试");
        }else {
            log.info("XxlUserKeyHandleJob RefreshKeyHandleJob 刷新用户ak sk成功..");
        }
    }

    /**
     * 每天刷新用户的ak sk
     */
    @XxlJob("RefreshDayTime")
    public void RefreshDayTime() {
        log.info("xxl-job RefreshDayTime 每天刷新用户刷新ak sk的剩余时间");
        List<User> userList = userService.list();
        List<User> list = userList.stream().map(user -> {
            Integer leftRefreshKeyTime = user.getLeftRefreshKeyTime();
            Integer isVip = user.getIsVip();
            if (leftRefreshKeyTime > 0 && isVip != UserConstant.ISVIP) {
                user.setLeftRefreshKeyTime(--leftRefreshKeyTime);
            }
            return user;
        }).collect(Collectors.toList());
        boolean saveBatch = userService.saveBatch(list);
        if (!saveBatch) {
            log.info("xxl-job RefreshDayTime 更新用户剩余刷新时间失败");
        }
        log.info("xxl-job RefreshDayTime 刷新用户ak sk成功..");
    }


}
